//
//  ViewController.m
//  ScrollTabBar
//  http://www.jianshu.com/p/ae247480f7d4
//  Created by mobao on 16/4/1.
//  Copyright © 2016年 mobao. All rights reserved.
//

#import "ViewController.h"

//屏幕宽高
#define SCREEN_WIDTH ([[UIScreen mainScreen] bounds].size.width)
#define SCREEN_HEIGHT ([[UIScreen mainScreen] bounds].size.height)

@interface ViewController ()<UIScrollViewDelegate>{
    int selectedIndex;
}

@end

@implementation ViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    _containerScrollView.delegate = self;
//    self.automaticallyAdjustsScrollViewInsets = NO;
    
    selectedIndex = 1;
    
    //初始化第一个图标为选中
    UIButton *button = [_tabBar viewWithTag:selectedIndex];
    button.selected = true;
    
}


//在以下方法中手动设置选项图标的水平间距
-(void)viewDidLayoutSubviews{
    [_containerScrollView setContentOffset:CGPointMake((selectedIndex - 1)*SCREEN_WIDTH, 0) animated:YES];
    CGFloat imageViewMarginLeft = (SCREEN_WIDTH-25 * 4)/8;
    _itemImgV1LeftMargin.constant = imageViewMarginLeft;
    _itemImgV2LeftMargin.constant = 2 * imageViewMarginLeft;
    _itemImgV3LeftMargin.constant = 2 * imageViewMarginLeft;
    _itemImgV4LeftMargin.constant = 2 * imageViewMarginLeft;
    
    [super viewDidLayoutSubviews];
}


//点击 选择图标，切换view以及选中的图标
- (IBAction)barButtonDidClicked:(UIButton *)sender {
    [self resetButton];
    
    UIButton *button = [_tabBar viewWithTag:sender.tag - 10];
    button.selected = true;
    
    NSLog(@"%f",(sender.tag -10- 1)*SCREEN_WIDTH);
    [_containerScrollView setContentOffset:CGPointMake((sender.tag -10- 1)*SCREEN_WIDTH, 0) animated:NO];
    
    selectedIndex = sender.tag;
}

//滚动停止时切换选中图标
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    CGFloat offsetX = scrollView.contentOffset.x;
    
    int selectedButtonIndex = offsetX/SCREEN_WIDTH + 1;
    
    [self resetButton];
    
    UIButton *button = [_tabBar viewWithTag:selectedButtonIndex];
    
    selectedIndex = selectedButtonIndex;
    
    button.selected = true;
    
}

//将按钮的selected全部置为false
-(void)resetButton{
    for (id item in _tabBar.subviews) {
        if ([item isKindOfClass:NSClassFromString(@"UIButton")] == true) {
            UIButton *button = item;
            button.selected = false;
        }
    }
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
